package com.smssalama.storage.contact;

import javax.microedition.rms.RecordFilter;

import com.smssalama.storage.framework.ObjectStorageException;
import com.smssalama.storage.framework.ObjectStore;
import com.smssalama.storage.framework.Storable;
import com.smssalama.storage.framework.StorableFilter;

/**
 * Filter for contacts used when searching for contacts from a contacts {@link ObjectStore}.
 * 
 * @author Arnold P. Minde
 */
public class ContactFilter implements RecordFilter, StorableFilter {

	private String contactName;
	private String phoneNumber;

	public ContactFilter(String contactName, String phoneNumber) {
		this.contactName = contactName;
		this.phoneNumber = phoneNumber;
	}

	public boolean matches(byte[] data) {
		try {
			Contact c = (Contact) Storable.init(data);
			return matches(c);
		} catch (ObjectStorageException ex) {
			return false;
		}
	}

	public boolean matches(Storable storable) {
		if(!(storable instanceof Contact)){
			return false;
		}
		Contact c = (Contact) storable;
		if (this.contactName != null) {
			if (!this.contactName
					.equalsIgnoreCase(c.getContactName() != null ? c
							.getContactName() : "")) {
				return false;
			}
		}
		if (this.phoneNumber != null) {
			if (!this.phoneNumber.equals(c.getPhoneNumber() != null ? c
					.getPhoneNumber() : "")) {
				return false;
			}
		}
		return true;
	}
}
